﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SIE.SCADA.Common;
using SIE.SCADA.SqlSugar;
using Model.Core;
using SIE.SCADA.StationDemo.Cache;
using Models;
using SIE.SCADA.ZemtDemo.Common;
using Newtonsoft.Json;
using SIE.SCADA.Common.Helper;
using SIE.SCADA.Common.Log;
//using SIE.SCADA.ZemtDemo.Common;
using System.Threading;
using SIE.SCADA.StationDemo.SerialCommunicat;
using SIE.SCADA.Helper;
using System.IO;
using System.Text.RegularExpressions;
using SIE.SCADA.StationDemo.Common;

namespace SIE.SCADA.StationDemo
{
    class StationController
    {
#if NETSTANDARD2_0
        LinuxScannDevice scannDevice;
        LinuxScannDevice writeDevice;
#else
        WinScannDevice scannDevice;
        WinScannDevice writeDevice;
#endif
        private readonly string start = "\u0002";
        private readonly string end = "\u0003";
        private readonly string end2 = "\u000D\u000A";
        private readonly string spac = "\u0000";
        private const string M400 = "M27#400Nm#WX";
        private const string M110 = "M20#110Nm#WX";
        private const string M70 = "M16#070Nm#WX";
        //private string _lastid = string.Empty;
        private string _lastid = "0";


        public static StationController CreateInstance()
        {
            if (instance == null)
            {
                lock (singleton_Lock)
                {
                    if (instance == null)
                    {
                        instance = new StationController();
                    }
                }
            }
            return instance;
        }

        #region 属性字段
        SignalLight SignalLight;
        private const string LastStepCode = "111111";  //重打上一步的特殊码
        private const string LastProceCode = "222222"; //重打整个工序的特殊码
        private const string ReProCode = "333333"; //重打指定一步的特殊码
        //private const string OfflineCode = "444444";
        private const string offline_S = "SMDC0001";
        private string _serverIp = "192.168.16.227";
        private bool _offlineMode = true;  //离线模式下所有数据都直接转发到写串口，默认离线模式
        private static StationController instance;
        private static object singleton_Lock = new object();
        protected AdvancedThread ThreadSend { get; set; }
        protected AdvancedThread ThreadSend2 { get; set; }
        protected AdvancedThread ThreadSend3 { get; set; }
        private int _disConnectcount = 3;
        private OrderMsg _OrderMsg;

        private Trackin trackin = new Trackin();
        string _barcode = "";//条码

        string EqStatus = "0";//状态,1:异常

        int _step = 0;

        /// <summary>
        /// 历史重打集合
        /// </summary>
        public List<v_scada_jobsteprecord> RecordRetry_List { get; set; }   //重打历史一步的工序信息
        /// <summary>
        /// 历史重打步
        /// </summary>
        public v_scada_jobsteprecord RecordRetryStep { get; set; }  //重打指定一步的工序信息
        private const string _deviceName = "Tag.ScanDevice";
        private const string _torqueDevice = "IO.扭力枪1";
        private ITag OrderNo;
        private ITag Curid;
        private ITag Torque;
        private ITag TorqueStatus;
        private ITag TimeStamp;
        private ITag JobID;
        private ITag TighteningStatus;
        private ITag AngleStatus;
        private ITag CellID;
        private ITag DisqueNo;
        private ITag Sn;
        private ITag BarCode;
        private ITag VINNumber;
        private ITag TighteningIDTag;
        private ITag TorqueFinalTarget;
        private ITag BatchCounter;
        private ITag BatchSize;
        private ITag BatchStatus;
        private ITag LastChangeParmeterSetTime;

        private ITag Angle;
        private ITag Tools;



        CacheConfig cacheConfig = new CacheConfig();
        CacheClient<scada_jobstep_record> JobRecordClient;
        CacheClient<TorqueParmas> TorqueRecordCacheClient;
        private ApiMeth apiMeth = new ApiMeth();
        #endregion

        public StationController()
        {
            if (!PortInit())
                ErrorRecord("串口初始化失败!");
            _serverIp = Env.StationConfig.ServerIP;
            JobRecordClient = new CacheClient<scada_jobstep_record>(cacheConfig, "JobstepRecord");
            TorqueRecordCacheClient = new CacheClient<TorqueParmas>(cacheConfig, "TorqueRecord");
            JobRecordClient.Start();
            TorqueRecordCacheClient.Start();
            WorkState = State.Wait;
            if (!TagInit())
                ErrorRecord("变量初始化失败!");
            if (TighteningIDTag != null) TighteningIDTag.ValueChanged += Status_ValueChanged;
            if (BarCode != null) BarCode.ValueChanged += BarCode_ValueChanged;
            //SignalLight?.Add(Color.Off);
            LightOff();
            Connect = Quality.defalutl;
            ThreadSend = new AdvancedThread(HearbeatConect, 0);
            ThreadSend.Start();

            ThreadSend2 = new AdvancedThread(ClockClick, 0);
            ThreadSend2.Start();

            ThreadSend3 = new AdvancedThread(Reset, 0);
            ThreadSend3.Start();



        }

        #region 初始化
        /// <summary>
        /// 串口的初始化
        /// </summary>
        /// <returns></returns>
        private bool PortInit()
        {
#if !NETSTANDARD2_0
            scannDevice = new WinScannDevice(Env.StationConfig.ScanPortname);
            writeDevice = new WinScannDevice(Env.StationConfig.WritePortname);
#else
            scannDevice = new LinuxScannDevice(Env.StationConfig.ScanPortname);
            writeDevice = new LinuxScannDevice(Env.StationConfig.WritePortname);
#endif
            scannDevice.ReceveChanged += ScannDevice_ReceveChanged;
            scannDevice.Start();
            writeDevice.Start();
            //指示灯
            SignalLight = new SignalLight(Env.StationConfig.LightPortname);
            SignalLight.Start();
            OrderInit();
            return true;
        }

        /// <summary>
        /// 变量初始化
        /// </summary>
        /// <returns></returns>
        private bool TagInit()
        {
            try
            {
                BarCode = ServerHostManager.GetServerHost().Project.Objects["Tag.ScanDevice.Bardcode"] as ITag;
                DisqueNo = ServerHostManager.GetServerHost().Project.Objects["Tag.ScanDevice.DisqueNo"] as ITag;
                Sn = ServerHostManager.GetServerHost().Project.Objects["Tag.ScanDevice.sn"] as ITag;
                OrderNo = ServerHostManager.GetServerHost().Project.Objects["Tag.ScanDevice.OrderNo"] as ITag;
                Curid = ServerHostManager.GetServerHost().Project.Objects["Tag.ScanDevice.Curid"] as ITag;

                Torque = ServerHostManager.GetServerHost().Project.Objects["IO.扭力枪1.Torque"] as ITag;
                //Angle = ServerHostManager.GetServerHost().Project.Objects["IO.扭力枪1.Angle"] as ITag;
                TorqueStatus = ServerHostManager.GetServerHost().Project.Objects["IO.扭力枪1.TorqueStatus"] as ITag;
                TimeStamp = ServerHostManager.GetServerHost().Project.Objects["IO.扭力枪1.TimeStamp"] as ITag;
                JobID = ServerHostManager.GetServerHost().Project.Objects["IO.扭力枪1.JobID"] as ITag;
                TighteningStatus = ServerHostManager.GetServerHost().Project.Objects["IO.扭力枪1.TighteningStatus"] as ITag;
                AngleStatus = ServerHostManager.GetServerHost().Project.Objects["IO.扭力枪1.AngleStatus"] as ITag;
                VINNumber = ServerHostManager.GetServerHost().Project.Objects["IO.扭力枪1.VINNumber"] as ITag;
                TighteningIDTag = ServerHostManager.GetServerHost().Project.Objects["IO.扭力枪1.TighteningID"] as ITag;
                BatchCounter = ServerHostManager.GetServerHost().Project.Objects["IO.扭力枪1.BatchCounter"] as ITag;
                BatchSize = ServerHostManager.GetServerHost().Project.Objects["IO.扭力枪1.BatchSize"] as ITag;
                BatchStatus = ServerHostManager.GetServerHost().Project.Objects["IO.扭力枪1.BatchStatus"] as ITag;
                TorqueFinalTarget = ServerHostManager.GetServerHost().Project.Objects["IO.扭力枪1.TorqueFinalTarget"] as ITag;

                Angle = ServerHostManager.GetServerHost().Project.Objects["IO.扭力枪1.Angle"] as ITag;
                //Tools = ServerHostManager.GetServerHost().Project.Objects["IO.扭力枪1.Tools"] as ITag;

                return true;
            }
            catch (Exception ex)
            {
                Logger.Error(ex.Message);
                Logger.Error(ex.StackTrace);
                return false;
            }
        }

        /// <summary>
        /// 客户端重启时把服务器当前的工单信息获取过来
        /// </summary>
        private void OrderInit()
        {
            var OrderMsg = apiMeth.SendRequestCurrOrder();
            if (OrderMsg != null)
            {
                _OrderMsg = OrderMsg;
                if (_OrderMsg.Cur_Process != null)
                {
                    CurProcess = _OrderMsg.Cur_Process;
                    Logger.Info($"当前服务器工单ID：{CurProcess?.id}");
                }
                if (OrderMsg.Error)
                {
                    ErrorRecord(OrderMsg.ErrorMsg);
                }
            }
        }
        #endregion

        #region 事件
        /// <summary>
        /// 串口事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ScannDevice_ReceveChanged(object sender, Common.BarcodeArg e)
        {
            new Thread(() =>
            {
                ValueChanged(e.Value);
                Logger.Info("条码数据（扫码枪）：" + e.Value);
            }).Start();
        }


        /// <summary>
        /// 串口事件(手动输入)
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BarCode_ValueChanged(object sender, TagChangedEventArgs e)
        {
            new Thread(() =>
            {
                ValueChanged(e.Value.ToString());
                Logger.Info("条码数据（手动输入）：" + e.Value.ToString());
            }).Start();
        }




        /// <summary>
        /// 扫码事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ValueChanged(string Bar)
        {
            _barcode = "";//条码
                          //_sn = "";//序列号
                          //_matid = "";//物料号
                          //_woid = "";//工单号

            //new Thread(() =>
            //{
            try
            {
                var barcode = Bar.Replace(start,"").Replace(end,"").Replace(end2,"").Replace(spac,"");
                _barcode = barcode;
                Logger.Info($"事件接收{barcode}！");
                if (string.IsNullOrEmpty(barcode)) return;

                //BarCode.Value = string.Empty;

                switch (barcode)
                {
                    case offline_S:
                        _offlineMode = !_offlineMode;
                        if (_offlineMode)
                        {
                            CurProcess = null;
                            Logger.Info("启用离线模式！");
                            SendMsg("启用离线模式");

                        }
                        else
                        {
                            Logger.Info("启用在线模式！");
                            SendMsg("启用在线模式");
                        }
                        break;

                    default:
                        if (!_offlineMode)
                        {
                            var OrderMsg = apiMeth.SendScanBardcode(barcode);

                            SendMsg("发送条码至服务端：" + barcode);
                            Logger.Info("发送条码至服务端：" + barcode);
                            if (OrderMsg != null)
                            {
                                _OrderMsg = OrderMsg;

                                if (_OrderMsg.Error)
                                {
                                    EqStatus = "1";//异常
                                    ErrorRecord(_OrderMsg.ErrorMsg);
                                }
                                else
                                {
                                    if (_OrderMsg.Cur_Prod != null)
                                    {
                                        CurProd = _OrderMsg.Cur_Prod;
                                        string bar2 = _OrderMsg.barcode;
                                        writeDevice?.WriteBarcode(Bar);
                                        _step = 1;

                                    }

                                }
                            }
                            else
                            {
                                ErrorRecord("返回Msg为NULL");
                                SendMsg("返回Msg为NULL");
                            }
                        }
                        else
                        {
                            writeDevice?.WriteBarcode(Bar);
                            //_step = 1;
                        }
                        break;
                }
            }
            catch (Exception ex)
            {
                Logger.Warn(ex.Message);
                Logger.Warn(ex.StackTrace);
            }
            //}).Start();
        }

        /// <summary>
        /// 采集事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Status_ValueChanged(object sender, TagChangedEventArgs e)
        {
            Thread.Sleep(100);
            var tighteningId = e?.Tag?.Value?.ToString() == null ? string.Empty : e?.Tag?.Value?.ToString();
            TighteningID = tighteningId;
            Logger.Info($"采集记录TightingID:{tighteningId}!");
            if (tighteningId != _lastid)// && !string.IsNullOrEmpty(_lastid))
            {
                DataChanged(tighteningId);
            }
            _lastid = tighteningId;
        }

        private void DataChanged(string id)
        {
            new Thread(() =>
            {
                try
                {
                    Thread.Sleep(800);
                    


                    if (id == null || id == "")
                    {
                        Logger.Info($"数据记录，tighteningId为空:{id}!");
                        return;
                    }
                    else {
                        Logger.Info($"数据记录，tighteningId:{id}!");

                    }


                    TorqueParmas torqueParmas = GetTorqueParmas();
                    torqueParmas.equipmentcode = Env.StationConfig.StationId;
                    torqueParmas.barcode = _barcode;
                    CheckBarcode barcodeInfo = trackin.GetListBarcodeInfo(_barcode);
                    torqueParmas.sn = barcodeInfo.SerialNumber;
                    torqueParmas.matid = barcodeInfo.ModeNumber;
                    torqueParmas.TimeStamp = DateTime.Now.ToString();

                    if (Connect == Quality.Good)
                    {
                        var torqueParmassendRes = apiMeth.SendTorqParam(torqueParmas);
                        SendMsg("发送扭力扳手数据，Barcode:" + _barcode);
                        //发送失败后,放到缓存
                        if (!torqueParmassendRes)
                        {
                            SaveTorqueMsgCache(torqueParmas);
                            ErrorRecord("发送扭力扳手数据失败！");
                        }
                    }
                    else
                    {
                        SaveTorqueMsgCache(torqueParmas);
                    }

                    
                    var list = new List<scada_jobstep_record>();
                    scada_jobstep_record JobStep = new scada_jobstep_record();

                    JobStep.equipmentcode = Env.StationConfig.StationId;
                    JobStep.vinnum = torqueParmas.VINNumber;
                    JobStep.torque = torqueParmas?.Torque.ObjToDecimal();
                    JobStep.torquefinaltarget = torqueParmas.TorqueFinalTarget;
                    JobStep.angle = torqueParmas.Angle.ObjToDecimal();
                    JobStep.torquestatus = torqueParmas.TorqueStatus.ObjToInt();
                    JobStep.anglestatus = torqueParmas.AngleStatus.ObjToInt();
                    JobStep.TighteningStatus = torqueParmas.TighteningStatus.ObjToInt();

                    JobStep.batchstatus = torqueParmas.BatchStatus.ObjToInt();
                    JobStep.batchcounter = torqueParmas?.BatchCounter;
                    JobStep.batchsize = torqueParmas?.BathSize.ObjToInt();
                    JobStep.tighteningid = torqueParmas.TighteningID;

                    JobStep.prodid = CurProd.id;
                    //JobStep.repair = barcodeInfo.RepairNumber;
                    JobStep.state_int = torqueParmas.TighteningStatus.ObjToInt();
                    JobStep.step = _step;
                    JobStep.createtime_dt = DateTime.Now;

                    list.Add(JobStep);
                    if (torqueParmas.TighteningStatus.ObjToInt() == 1)
                    {
                        _step += 1;//步数加1
                    }
                    //离线模式不发送工步数据
                    if (!_offlineMode)
                    {

                        if (Connect == Quality.Good)
                        {
                            var jobStepSendRes = apiMeth.SendUpdateRecord(list);
                            SendMsg("发送工步数据");
                            if (!jobStepSendRes)
                            {
                                //发送失败后,放到缓存
                                SaveOrderMsgCache(JobStep);
                                ErrorRecord("发送工步数据失败！");
                            }
                        }
                        else
                        {
                            //放到缓存
                            SaveOrderMsgCache(JobStep);
                        }
                    }

                }
                catch (Exception ex)
                {
                    Logger.Warn(ex.Message);
                    Logger.Warn(ex.StackTrace);
                }
            }).Start();
        }

        #endregion
        /// <summary>
        /// 获取扭力扳手数据
        /// </summary>
        /// <returns></returns>
        private TorqueParmas GetTorqueParmas()
        {
            TorqueParmas torqueParmas = new TorqueParmas();
            try
            {
                torqueParmas.VINNumber = VINNumber?.Value?.ToString();
                torqueParmas.JobID = JobID?.Value.ToString();

                torqueParmas.Torque = Torque?.Value.ToString();
                torqueParmas.TorqueFinalTarget = TorqueFinalTarget?.Value.ToString();
                torqueParmas.Angle = Angle?.Value.ToString();

                torqueParmas.AngleStatus = AngleStatus?.Value.ToString();
                torqueParmas.TorqueStatus = TorqueStatus?.Value.ToString();
                torqueParmas.TighteningStatus = TighteningStatus?.Value.ToString();

                torqueParmas.BathSize = BatchSize?.Value.ToString();
                torqueParmas.BatchCounter = BatchCounter?.Value.ToString();
                torqueParmas.BatchStatus = BatchStatus?.Value.ToString();

                torqueParmas.TighteningID = TighteningIDTag?.Value.ToString();
                if (_offlineMode)
                {
                    torqueParmas.Tools = "离线";
                }
                else {

                    torqueParmas.Tools = "在线";
                }

            }
            catch (Exception ex)
            {
                Logger.Error(ex.Message);
                Logger.Warn(ex.StackTrace);
            }
            return torqueParmas;
        }

        /// <summary>
        /// 记录错误信息并输出指示灯
        /// </summary>
        private void ErrorRecord(string msg = "")
        {

            //SendMsg($"返回错误信息:{msg}");
            Logger.Warn($"返回错误信息:{msg}");
        }

        private void Test()
        {

        }

        private void TestReg()
        {
            var str = "\u0002s23456687s7\u0003";
            Regex regex = new Regex($@"(?<={start}).*?(?={end})");
            var result = regex.Match(str).Value;
        }

        /// <summary>
        ///// 客户端过站
        ///// </summary>
        ///// <param name="_Scada_Jobsteprecord"></param>
        //private void OverStation(scada_jobstep_record jobstep)
        //{
        //    if (jobstep != null)
        //    {
        //        var list = new List<scada_jobstep_record>();
        //        list.Add(jobstep);
        //        var sendRes = apiMeth.SendUpdateRecord(list);
        //        //api数据发送成功
        //        if(!sendRes)
        //        {
        //            //发送失败后,放到缓存
        //            SaveOrderMsgCache(jobstep);
        //            ErrorRecord("过站数据提交失败！");
        //        }
        //    }
        //}

        /// <summary>
        /// 心跳连接
        /// </summary>
        private void HearbeatConect()
        {

            var arrlist = new List<object>();
            arrlist.Add(Env.StationConfig.StationId);
            try
            {
                var res = ApiHelper.Post<bool>("Heartbeat", arrlist.ToArray(), Env.StationConfig.ServerIP);

                if (res.IsSuccess)
                {

                    if (!res.Data)
                    {
                        _disConnectcount++;
                    }
                    else
                    {
                        _disConnectcount = 0;
                        Connect = Quality.Good;
                    }
                }

                if (_disConnectcount >= 3)
                {
                    Connect = Quality.Bad;
                    Logger.Warn("连接服务器超时2，" + Env.StationConfig.StationId);
                }
            }
            catch (Exception ex)
            {
                Logger.Warn("连接服务器异常2，" + ex.Message);
                Logger.Warn(ex.StackTrace);
            }


            Thread.Sleep(2000);
        }

        /// <summary>
        /// 
        /// </summary>
        private void ClockClick()
        {

            try
            {
                if (_offlineMode)
                {
                    //lastLightStatus = 1;
                    Warnning();
                }
                else if (Connect == Quality.Bad)
                {
                    //lastLightStatus = 2;
                    Error();
                }
                else if (EqStatus == "1")
                {
                    Alarm();

                }
                else
                {
                    Normal();
                    //lastLightStatus = 3;
                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex.Message);
                Logger.Error(ex.StackTrace);
            }
            Thread.Sleep(500);
        }



        /// <summary>
        /// 
        /// </summary>
        private void Reset()
        {

            try
            {
                if (EqStatus == "1")
                {
                    Thread.Sleep(5000);
                    EqStatus = "0";
                }

            }
            catch (Exception ex)
            {
                Logger.Error(ex.Message);
                Logger.Error(ex.StackTrace);
            }
            Thread.Sleep(500);
        }

        #region 缓存功能
        /// <summary>
        /// 离线数据恢复
        /// </summary>
        /// <returns></returns>
        private bool JobRecordRecory()
        {
            try
            {
                var path = string.Empty;
                var cache = JobRecordClient?.GetCacheFile(out path);
                if (cache.Any())
                {
                    if (apiMeth.SendRecoveryRecord(cache, "RecoveryState"))
                        File.Delete(path);
                    return true;
                }
            }
            catch (Exception ex)
            {
                Logger.Warn(ex.Message);
                Logger.Warn(ex.StackTrace);
            }
            return false;
        }

        /// <summary>
        /// KJF 20210323 新增
        /// 扭力扳手离线数据恢复
        /// </summary>
        /// <returns></returns>
        private bool TorqueRecordRecory()
        {
            try
            {
                var path = string.Empty;
                var cache = TorqueRecordCacheClient?.GetCacheFile(out path);
                if (cache.Any())
                {
                    if (apiMeth.SendRecoveryRecord<TorqueParmas>(cache, "RecoveryTorqueRecord"))
                        File.Delete(path);
                    return true;
                }
            }
            catch (Exception ex)
            {
                Logger.Warn(ex.Message);
                Logger.Warn(ex.StackTrace);
            }
            return false;
        }

        /// <summary>
        /// 订单信息存到内存
        /// </summary>
        private void SaveOrderMsgCache(scada_jobstep_record v_Scada_Jobsteprecord)
        {
            JobRecordClient?.Add(v_Scada_Jobsteprecord);
        }

        /// <summary>
        /// KJF 20210323 新增
        /// 扭力扳手信息存到内存
        /// </summary>
        private void SaveTorqueMsgCache(TorqueParmas torquerecord)
        {
            TorqueRecordCacheClient?.Add(torquerecord);
        }

        #endregion

        #region 重打

        /// <summary>
        /// 扫码 重打上一个工序
        /// </summary>
        private bool RetryLastProcess()
        {
            return apiMeth.SendRetryProcess();
        }
        #endregion

        #region 指示灯控制
        /// <summary>
        /// 错误
        /// </summary>
        private void Error()
        {
            SignalLight?.Add(Color.Red);
        }

        /// <summary>
        /// 警报
        /// </summary>
        private void Alarm()
        {
            SignalLight?.Add(Color.RedAndAlarm);
        }


        /// <summary>
        /// 正常
        /// </summary>
        private void Normal()
        {
            SignalLight?.Add(Color.Green);

        }

        /// <summary>
        /// 警告信息
        /// </summary>
        private void Warnning()
        {
            SignalLight?.Add(Color.Yellow);
        }

        /// <summary>
        /// 灯灭
        /// </summary>
        private void LightOff()
        {
            SignalLight?.Add(Color.Off);
        }

        /// <summary>
        /// 正常
        /// </summary>
        private void Noramal(string Msg)
        {
            SignalLight?.Add(Color.Green);
            apiMeth.SendClientMsg(Msg);
        }

        /// <summary>
        /// KJF 20210326 新增
        /// </summary>
        private void SendMsg(string Msg = "")
        {
            apiMeth.SendClientMsg(Msg);
            //Logger.Info(Msg);
        }


        #endregion

        public scada_jobstep_record RetryJobStep { get; set; }

        public scada_process_record CurProcess { get; set; }

        public scada_product_info CurProd { get; set; }

        private string _TighteningID;

        public string TighteningID
        {
            get { return _TighteningID; }
            set
            {
                if (value != _TighteningID)
                {
                    _TighteningID = value;
                }
            }
        }

        private int _curId;

        public int CurId
        {
            get
            {
                return Convert.ToInt32(Curid.Value);
            }
            set { _curId = value; }
        }

        /// <summary>
        /// 工作状态
        /// </summary>
        public State WorkState { get; set; }

        public void Stop()
        {
            SignalLight?.Stop();
            scannDevice?.Stop();
            writeDevice?.Stop();
        }

        private Quality _connect;

        public Quality Connect
        {
            get { return _connect; }
            set
            {
                if (value != _connect)
                {
                    _connect = value;
                    if (Quality.Good == value)
                    {
                        SendMsg("通讯正常");
                        JobRecordRecory();
                        TorqueRecordRecory();

                    }
                    else if (Quality.Bad == value)
                    {

                    }
                }
            }
        }

        public enum Quality
        {
            defalutl,
            Good,
            Bad,
        }

    }
}
